package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"log"
	"net"
	"os"
	"strings"
	"unsafe"
)

// 与客户端通信的结构
type ClientMsg struct {
	To      string  `json:"to"`       //去哪
	Msg     string  `jason:"msg"`     //内容
	Datalen uintptr `jason:"datalen"` //数据长度
}

// 用户帮助
func Help() {
	fmt.Println("set: your name")
	fmt.Println("all: your msg -- broadcadt")
	fmt.Println("anyone: your msg -- private msg")
}
func main() {
	//连接
	conn, err := net.Dial("tcp", "127.0.0.1:8888")
	if err != nil {
		log.Panic("dialing failed!", err)
	}
	defer conn.Close()
	//通信
	go handle_conn(conn)
	//读标准输入
	reader := bufio.NewReader(os.Stdin)
	fmt.Printf("Welcome to chatroom\n")
	Help()
	for {
		fmt.Printf("chatroom>")
		msg, err := reader.ReadString('\n')
		if err != nil {
			panic("reading string failed!")
		}
		msg = strings.Trim(msg, "\r\n")
		if msg == "quit" {
			fmt.Println("bye~")
			break
		}
		if msg == "help" {
			Help()
			continue
		}
		//消息传输格式处理
		msgs := strings.Split(msg, ":")
		if len(msgs) == 2 {
			var climsg ClientMsg
			climsg.To = msgs[0]
			climsg.Msg = msgs[1]
			climsg.Datalen = unsafe.Sizeof(climsg)
			data, err := json.Marshal(climsg)
			if err != nil {
				fmt.Println("marshaling failed", err, climsg)
				continue
			}
			_, err = conn.Write(data)
			if err != nil {
				fmt.Println("writing failed", err, data)
				break
			}
		}
	}
}
func handle_conn(conn net.Conn) {
	buf := make([]byte, 256)
	//red := "\033[31m"
	reset := "\033[0m"
	green := "\033[32m"
	yellow := "\033[33m"
	for {
		n, err := conn.Read(buf)
		if err != nil {
			panic("reading failed!")
		}
		msg := string(buf[:n])
		if strings.Contains(msg, "all") {
			fmt.Println(green + string(buf[:n]) + reset)
		} else {
			fmt.Println(yellow + string(buf[:n]) + reset)
		}

		fmt.Printf("chatroom>")
	}
}
